// TorrentUpload.jsx
import { useState } from "react";
import { Upload, Button, Form, Input, Select, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import axios from "axios";
import { getAuthToken } from "@/router";

export default function TorrentUpload({ onClose, onSuccess }) {
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [loading, setLoading] = useState(false);

  const handleUpload = async (values) => {
    if (fileList.length === 0) {
      message.error("请选择种子文件");
      return;
    }

    const formData = new FormData();
    formData.append("file", fileList[0]);
    formData.append("name", values.name);
    formData.append("category", values.category);
    formData.append("tags", values.tags);
    formData.append("description", values.description);

    try {
      setLoading(true);
      // 这里上传没有配置当前上传是否是双倍积分的参数？
      const res = await axios.post(
        "http://192.168.55.192:8080/api/torrent/upload",
        formData,
        {
          headers: {
            Authorization: `${getAuthToken()}`,
            "Content-Type": "multipart/form-data",
          },
        }
      );

      message.success(
        `上传成功！种子ID: ${res.data.data.id}，哈希值: ${
          res.data.data.infoHash
        }，大小: ${(res.data.data.size / 1024).toFixed(2)}KB`
      );
      form.resetFields();
      setFileList([]);
      onSuccess();
    } catch (error) {
      message.error(error.response?.data?.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="upload-content">
      <Form
        form={form}
        onFinish={handleUpload}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
      >
        <Form.Item
          name="name"
          label="资源名称"
          rules={[
            { required: true, message: "请输入资源名称" },
            { max: 100, message: "名称最多100个字符" },
          ]}
        >
          <Input placeholder="例如：阿凡达.2009.BluRay.1080p" />
        </Form.Item>

        <Form.Item
          name="category"
          label="分类"
          rules={[{ required: true, message: "请选择分类" }]}
        >
          <Select
            placeholder="请选择资源分类"
            options={[
              { value: "1", label: "电影" }, // 改为字符串类型以匹配后端
              { value: "2", label: "剧集" },
              { value: "3", label: "音乐" },
            ]}
          />
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
          rules={[{ required: true, message: "请输入标签" }]}
        >
          <Input placeholder="多个标签用逗号分隔，例如：动作,4K" />
        </Form.Item>

        <Form.Item
          name="description"
          label="描述"
          rules={[{ max: 500, message: "描述最多500个字符" }]}
        >
          <Input.TextArea
            rows={3}
            placeholder="例如：4K REMUX版本，包含中英双语字幕"
          />
        </Form.Item>

        <Form.Item
          label="种子文件"
          required
          extra="仅支持.torrent文件，大小不超过100MB"
        >
          <Upload
            fileList={fileList}
            accept=".torrent"
            maxCount={1}
            beforeUpload={(file) => {
              if (file.size > 100 * 1024 * 1024) {
                message.error("文件大小超过100MB限制");
                return Upload.LIST_IGNORE;
              }
              setFileList([file]);
              return false;
            }}
            onRemove={() => setFileList([])}
          >
            <Button icon={<UploadOutlined />} disabled={fileList.length >= 1}>
              选择文件
            </Button>
          </Upload>
        </Form.Item>

        <div className="form-footer">
          <Button onClick={onClose} style={{ marginRight: 16 }}>
            取消
          </Button>
          <Button type="primary" htmlType="submit" loading={loading}>
            {loading ? "上传中..." : "提交上传"}
          </Button>
        </div>
      </Form>
    </div>
  );
}
